#include "XnccEventfd.h"
#include "Util.h"
namespace xncc {
namespace sys {

    EventFd::EventFd()
    {
#if defined(__CYGWIN__)
        auto ret = pipe(pipe_fd_);
        if (ret == -1) {
            throw shared::system_exception("create pipe");
        }
        event_fd_ = pipe_fd_[0];  // 读事件
#else
        event_fd_ = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC | EFD_SEMAPHORE);
#endif
        if (event_fd_ < 0) {
            throw shared::system_exception("create eventfd failed");
        }
    }
    EventFd::~EventFd()
    {
#if defined(__CYGWIN__)

        close(pipe_fd_[1]);
        close(pipe_fd_[0]);
#else
        close(event_fd_);
#endif
    }

    ssize_t EventFd::read(uint64_t& flag) const
    {
        uint64_t num = 0;
        auto     ret = ::read(event_fd_, &num, sizeof(num));
        flag         = num;
        return ret;
    }

    ssize_t EventFd::write(uint64_t flag) const
    {
#if defined(__CYGWIN__)
        return ::write(pipe_fd_[1], &flag, sizeof(flag));
#else
        return ::write(event_fd_, &flag, sizeof flag);
#endif
    }
}  // namespace sys
}  // namespace xncc
